package com.link.base.base.common.utils;

import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;


import java.util.*;

/**
 * Copyright (C) 2000-2018 Kohler Company. All Rights Reserved.
 * <p>
 * Purpose of the class or interface appears here as a description.
 *
 * @author yrf
 * @version 1.0
 * @date: 2018/11/29 13:56
 * @update zhuyipeng
 */

public class SendSmsUtil {
    /**
     * 每天所能发送短信的总次数
     */
    public static final int  ALL_PHONENUM_SENDTIMES_LIMIT_ONEDAY = 1000;

    /**
     * 每天每个手机号所能发送短信的次数
     */
    public static final int  SINGLE_PHONENUM_SENDTIMES_LIMIT_ONEDAY = 10;

    /**
     * 计算总发送短信次数key；后面拼接上手机号表示该手机号的短信发送次数
     */
    public static final String   REDISKEY_FORMSG_TOTAL_PREFIX = "MsgCounter#";

    /**
     * 某手机号已接收信息次数（当天）
     */
    public static final String  REDIS_FIELD_TOTAL = "Total";

    /**
     * 手机号（当天）首次接收信息的系统时刻，毫秒
     */
    public static final String  REDIS_FIELD_TIME = "Time";


    /**
     * <p>保存最近发送短信内容24小时, key为msgType+phoneNumber；Field 'Time' 为发送时间戳（毫秒）</p>
     * @author yrf
     * @param phoneNumber  手机号码
     * @param templateCode 短信模板编码
     * @param param        短信内容
     * @param msgType      短信类型
     */
    public static void upsertMsgType(String phoneNumber, String templateCode,
                                     Map<String, String> param, String msgType) {
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            String redisKey = msgType + phoneNumber;
            jedis.hmset(redisKey, param);
            jedis.hset(redisKey, "Time", String.valueOf(System.currentTimeMillis()));
            jedis.hset(redisKey, "TemplateCode", templateCode);
            jedis.expire(redisKey, 24 * 60 * 60);
        } finally {
            RedisUtil.returnResource(jedis);
        }

    }

    /**
     * <p>短信发送前校验，返回null表示校验通过</p>
     * @author yrf
     * @param phoneNumber
     * @return json字符串
     */
    public static String beforeSend(String phoneNumber) {
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            String redisKey = REDISKEY_FORMSG_TOTAL_PREFIX + phoneNumber;
            Long startTime = getThisDayStartTime();
            Long endTime = getThisDayEndTime();
            //该号码当天已发送次数
            String totalStr = jedis.hget(redisKey, REDIS_FIELD_TOTAL);
            //该号码当天第一次发送时间
            String timeStr = jedis.hget(redisKey, REDIS_FIELD_TIME);

            /** 发送总次数校验 */
            //当天已发送总次数
            String allTotalStr = jedis.hget(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TOTAL);
            //当天开始统计时间
            String allTimeStr = jedis.hget(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TIME);
            if (allTotalStr != null && allTimeStr != null) {
                int allTotal = Integer.valueOf(allTotalStr);
                long allTime = Long.valueOf(allTimeStr);
                if (startTime <= allTime && allTime <= endTime) {
                    if (allTotal >= ALL_PHONENUM_SENDTIMES_LIMIT_ONEDAY) {
                        String errorMsg = "您好，" + phoneNumber + "很抱歉当前系统发送验证码次数已超出限制，今天暂时内无法再发送信息！";
                        return "{\"success\":false,\"result\":\"" + errorMsg + "\"}";
                    }
                }
            }

            /** 当前手机号发送次数校验 */
            if (totalStr == null || timeStr == null) {
                return null;
            } else {
                int total = Integer.valueOf(totalStr);
                long time = Long.valueOf(timeStr);
                if (time >= startTime && endTime >= time) {
                    //该手机号的发送统计信息时间当天内有效
                    if (total >= SINGLE_PHONENUM_SENDTIMES_LIMIT_ONEDAY) {
                        String errorMsg = "该号码【" + phoneNumber + "】今天发送" + total + "次，请勿频繁发送";
                        return "{\"success\":false,\"result\":\"" + errorMsg + "\"}";
                    }
                }

            }
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return null;
    }

    /**
     * <p>发送短信后设置已发送次数加一</p>
     * @author yrf
     * @param phoneNumber
     */
    public static void afterSend(String phoneNumber) {
        LinkRedisClient jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            String redisKey = REDISKEY_FORMSG_TOTAL_PREFIX + phoneNumber;
            Long timeStamp = System.currentTimeMillis();
            Long startTime = getThisDayStartTime();
            Long endTime = getThisDayEndTime();
            String totalStr = jedis.hget(redisKey, REDIS_FIELD_TOTAL);
            String timeStr = jedis.hget(redisKey, REDIS_FIELD_TIME);

            /** 发送总次数加一 */
            //当天已发送总次数
            String allTotalStr = jedis.hget(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TOTAL);
            //当天开始统计时间
            String allTimeStr = jedis.hget(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TIME);
            if (allTotalStr != null && allTimeStr != null) {
                int allTotal = Integer.valueOf(allTotalStr);
                jedis.hset(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TOTAL, String.valueOf(allTotal + 1));
                jedis.hset(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TIME, String.valueOf(timeStamp));
            } else {
                jedis.hset(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TOTAL, "1");
                jedis.hset(REDISKEY_FORMSG_TOTAL_PREFIX, REDIS_FIELD_TIME, String.valueOf(timeStamp));
            }

            /** 手机号发送次数加一 */
            if (totalStr == null || timeStr == null) {
                jedis.hset(redisKey, REDIS_FIELD_TOTAL, "1");
                jedis.hset(redisKey, REDIS_FIELD_TIME, String.valueOf(timeStamp));
                jedis.expire(redisKey, (int) ((endTime - timeStamp) / 1000));
            } else {
                int total = Integer.valueOf(totalStr);
                long time = Long.valueOf(timeStr);
                if (time >= startTime && endTime >= time) {
                    //该手机号的发送统计信息时间当天内有效
                    jedis.hset(redisKey, REDIS_FIELD_TOTAL, String.valueOf(total + 1));
                } else {
                    jedis.hset(redisKey, REDIS_FIELD_TOTAL, "1");
                    jedis.hset(redisKey, REDIS_FIELD_TIME, String.valueOf(timeStamp));
                    jedis.expire(redisKey, (int) ((endTime - timeStamp) / 1000));
                }
            }
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    /**
     * <p>获取当天开始时间（00：00：00）的毫秒数</p>
     * @author yrf
     * @return
     */
    public static long getThisDayStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date start = calendar.getTime();
        return start.getTime();
    }

    /**
     * <p>获取当天结束时间（23：59：59）的毫秒数</p>
     * @author yrf
     * @return
     */
    public static long getThisDayEndTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date end = calendar.getTime();
        return end.getTime();
    }

    public static String getRequestStatus(int idex) {
        String requestStatus;
        if (0 == idex) {
            requestStatus = "SUCCESS";
        } else {
            requestStatus = "FAIL";
        }
        return requestStatus;
    }

}

